import axios from 'axios'
import { Dialog, Toast } from 'react-vant'

const http = axios.create()
http.defaults.timeout = 10000

// 请求拦截
http.interceptors.request.use(
  async (config: any) => {
    config.headers.openId = localStorage.getItem('openId') || undefined
    return config
  },
  (error: any) => {
    console.log(error) // for debug
    return Promise.reject(error)
  },
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res?.msg === '登录错误') {
      localStorage.clear()
      Dialog.alert({
        title: '授权异常',
        message: '授权异常，请重新登录',
        onConfirm() {
          window.location.href = '/'
        },
      })
    }
    if (res?.state === 'fail') {
      res?.msg && Toast(res?.msg)
      return Promise.reject(res)
    };

    return res
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default http
